package com.lwx.sort;

import java.util.Arrays;
import java.util.Random;

//选择排序
//1.假设第0位是最小值，如果找到比arr[0]小的值，记录下minIndex,将最小值与初始值交换
//2.arr[0...minIndex-1]是有序区，每次比较从minIndex开始比较
public class SelectSortDemo {
    public static void main(String[] args) {
        int n = 1000;
        int[] arr = new int[n];
        for (int i = 0; i <n ; i++) {
            arr[i] = new Random().nextInt(1000);
        }
        System.out.println("排序前"+ Arrays.toString(arr));
        SelectSort(arr);
        for (int i = 0; i < arr.length-1; i++) {
            if(arr[i] > arr[i+1]){
                throw new IllegalArgumentException("排序失败");
            }
        }
        System.out.println("排序后"+ Arrays.toString(arr));
        System.out.println("Completed!");
    }

    public static void SelectSort(int[] arr){
        for (int i = 0; i < arr.length-1; i++) {
            int minIndex = i;
            for (int j = i+1; j < arr.length; j++) {
                if(arr[j] < arr[minIndex]){
                    minIndex = j;
                }
            }
            int tmp = arr[i];
            arr[i] = arr[minIndex];
            arr[minIndex] = tmp;
        }
    }
}
